const wifi = require('Wifi');
const http = require('http');


function getParams(url){
    const urls = url.split('?');
    if(urls.length<1){
        return {}
    }
    const paramsStrs = String(urls[1]).split('&');
    const params = {};
    paramsStrs.forEach(str=>{
       const detail = str.split('=');
       if(detail.length){
           params[detail[0]]=detail[1]||''
       }
    });
    return params;
}

function connectWifi(ssid, password, cb) {
    wifi.connect(ssid, {
        password: password
    }, function (ap) {
        if (ap === null) {
            wifi.save();
        }
        if (typeof cb === 'function') {
            cb();
        }
    });
}

function startLight() {
    let ledStatus = false;
    setInterval(()=>{
        console.log(ledStatus)
        digitalWrite(NodeMCU.D4,ledStatus)
        ledStatus = !ledStatus;
    },3000)
}

let ledStatus = true;
let interval = null
function createServer(port) {
    var server = http.createServer(function (req, res) {
        const params = getParams(req.url)
        if(params.a==='1'){
            ledStatus = true
            interval=  setInterval(()=>{
                console.log('light',Date.now());
                digitalWrite(NodeMCU.D4,ledStatus);
                ledStatus = !ledStatus
            },1000)
        }

        if(params.a==='2'){
            if(interval){
                clearInterval(interval);
                interval = null;
            }
        }

        res.writeHead(200, {
            'Content-Type': "text/html"
        });
        res.end(`<html><body>${JSON.stringify(params)}</body></html>`)
    })
    server.listen(port);
    console.log(wifi.getIP().ip);
}


function init() {
    connectWifi('HB', '12345654321', function (ap) {
        if (!ap) {
            createServer(81);
            console.log('service-start');
        } else {
            console.log('wifi-fail');
        }
    });
}

init();